package com.xq.sqlSession;

import com.xq.pojo.Configuration;
import com.xq.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> findAll(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<Object> all = simpleExecutor.findAll(configuration, mappedStatement, params);
        return (List<E>) all;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = findAll(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("结果集不止一个或者为空");
        }
    }

    @Override
    public <T> T getMapperClass(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String name = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + name;
                Type type = method.getGenericReturnType();
                //处理泛型的type 查询
                if (type instanceof ParameterizedType) {
                    return findAll(statementId, args);
                } else if (type.getTypeName().equals("int")) {
                    return doUpdate(statementId, args);
                } else {
                    return selectOne(statementId, args);
                }

            }
        });
        return (T) proxyInstance;
    }

    @Override
    public int doUpdate(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        int i = simpleExecutor.doUpdate(configuration, mappedStatement, params);
        return i;
    }
}
